<template>
    <div class="upload">
        <el-upload
            ref="imgUpload"
            list-type="picture-card"
            :action="action"
            :headers="headers"
            :accept="accept"
            :limit="limit"
            :file-list="fileList"
            :before-upload="beforeUpload"
            :on-exceed="handleExceed"
            :on-success="handleSuccess"
            :on-preview="handlePicturePreview"
            :on-change="handleChange"
            :on-remove="handleRemove"
            multiple
        >
            <i class="el-icon-plus" />
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
    </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import { UploadOption, ResponseCode } from '@/config/constants'
import { fileTokenKey } from '@/config/settings'

export default {
    name: 'ImageUpload',
    props: {
        value: {
            type: Object,
            default: () => {}
        },
        title: {
            type: String,
            default: '缺陷内容'
        },
        list: {
            type: Array,
            default: () => []
        },
        limit: {
            type: Number,
            default: UploadOption.LIMIT
        },
        size: {
            type: Number,
            default: 20
        }
    },
    data() {
        return {
            dialogVisible: false,
            dialogImageUrl: '',
            headers: {
                [fileTokenKey]: getToken()
            },
            action: UploadOption.ACTION,
            accept: UploadOption.ACCEPT,
            fileList: [],
            imgList: []
        }
    },
    computed: {
        showDelete() {
            return this.formList?.length > 1
        }
    },
    watch: {
        imgList: {
            handler(newval) {
                if (!newval) {
                    return
                }
                const disabled = newval.some((item) => item.status && item.status !== 'success')
                this.$emit('update:over', disabled)
                this.$emit('update:list', newval)
            },
            deep: true
        },
        // 监听回传的文件列表
        list: {
            handler(newval) {
                console.log('list>>>', newval)
                this.fileList = newval
                this.imgList = this.fileList
            },
            deep: true,
            immediate: true
        }
    },
    methods: {
        beforeUpload(file) {
            // 如果files里有相同name文件，说明已经上传过同名文件
            const length = this.imgList.filter((item) => item.name === file.name).length
            if (length >= 2) {
                this.$message.error(`已经上传相同名称文件${file.name}`)
                return false
            }

            // 文件大于size的禁止上传
            if (file.size / 1024 / 1024 > this.size) {
                this.$message.error(`文件${file.name}大小超过${this.size}MB`)
                return false
            }
            return true
        },
        handleExceed(files, fileList) {
            if (fileList?.length >= this.limit) {
                this.$message.warning(`已经上传 ${this.limit}张图片，不能再上传了`)
                return
            }
            this.$message.warning(`最多上传 ${this.limit} 张照片，本次选择了 ${files.length} 个照片`)
        },
        handleSuccess(response, file, fileList) {
            if (response.code === ResponseCode.success) {
                this.imgList = fileList
            } else {
                fileList.some((item, index) => {
                    if (item.uid === file.uid) {
                        fileList.splice(index, 1)
                        return true
                    }
                })
                this.$message.error('文件上传失败，请重试！')
            }
        },
        handleChange(file, fileList) {
            this.imgList = fileList
        },
        handleRemove(file) {
            this.imgList.some((item, index) => {
                if (item.uid === file.uid) {
                    this.imgList.splice(index, 1)
                    return true
                }
            })
        },
        handlePicturePreview(file) {
            this.dialogImageUrl = file.url
            this.dialogVisible = true
        }
    }
}
</script>
